package com.jean.business.user.controller;

import java.sql.SQLException;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.ibatis.sqlmap.client.SqlMapClient;
import com.jean.business.RespFactory;
import com.jean.business.bean.UserInfo;
import com.jean.business.bean.UserSessionContent;
import com.jean.business.event.req.UserSignInRequest;
import com.jean.business.event.resp.BaseResp;
import com.jean.business.event.resp.SimpleResp;
import com.jean.business.user.UserSessionManage;
import com.jean.common.ConstantConfigs;
import com.jean.common.ConstantReturnCode;
import com.jean.init.MusicContext;
import com.jean.util.EncryptTool;
import com.jean.util.LoggerFactory;

/**
 * <一句话功能简述>user账户管理控制层 <功能详细描述>
 * 
 * @author Jean
 * @version [版本号, 2013年12月8日]
 * @see [相关类/方法]
 * @since [产品/模块版本]
 */
@Controller
@RequestMapping(ConstantConfigs.REQUEST_MODULE_USER)
public class UserAccountManageController
{
    /**
     * 日志
     */
    private static Logger logger = LoggerFactory.getLogger();
    
    /**
     * 是否刷新session标识
     */
    private static boolean USER_REFRESH_SESSION_FLAG = false;
    
    /**
     * <一句话功能简述>用户登录接口 <功能详细描述>
     * 
     * @param request 请求
     * @param account 账号
     * @param password 密码
     * @return 登录结果
     * @see [类、类#方法、类#成员]
     */
    @RequestMapping("/signin")
    @ResponseBody
    public BaseResp login(HttpServletRequest request,
        HttpServletResponse response, UserSignInRequest userSignInRequest)
    {
        logger.info("user sign in control start...");
        BaseResp resp = new BaseResp();
        if (StringUtils.isEmpty(userSignInRequest.getNickName())
            && StringUtils.isEmpty(userSignInRequest.getEmail())
            || StringUtils.isEmpty(userSignInRequest.getPassword()))
        {
            logger.warn("admin sign in fail, the mandatory parameter is empty.");
            resp =
                RespFactory.getResp(request,
                    ConstantReturnCode.MUSIC_PARAMETER_EMPTY);
            return resp;
        }
        
        // 获取调用的sql语句
        String sql =
            StringUtils.isEmpty(userSignInRequest.getNickName()) ? "queryUserByEmail"
                : "queryUserByNickName";
        UserInfo sqlParam = new UserInfo();
        sqlParam.setNickName(userSignInRequest.getNickName());
        sqlParam.setEmail(userSignInRequest.getEmail());
        sqlParam.setPassword(EncryptTool.encrypt(userSignInRequest.getPassword()));
        
        SqlMapClient sqlMapClient = MusicContext.getSqlMapClient();
        UserInfo userInfo = new UserInfo();
        try
        {
            userInfo = (UserInfo)sqlMapClient.queryForObject(sql, sqlParam);
        }
        catch (SQLException e)
        {
            logger.error("SqlMapClient query userinfo error", e);
            resp =
                RespFactory.getResp(request,
                    ConstantReturnCode.MUSIC_DATABASE_ABNORMAL);
            return resp;
        }
        if (userInfo == null)
        {
            logger.warn("User sign in failed.");
            resp =
                RespFactory.getResp(request,
                    ConstantReturnCode.MUSIC_LOGIN_FAIL);
            return resp;
        }
        
        // 登录成功，将user账号信息存入session
        request.getSession().setAttribute(ConstantConfigs.SESSION_USERINFO,
            userInfo);
        
        // 解決https跳转http，session失效的问题
        Cookie cookie = new Cookie("JSESSIONID", request.getSession().getId());
        response.addCookie(cookie);
        
        // 下次第一次调用checklogin时，刷新session
        USER_REFRESH_SESSION_FLAG = true;
        resp = RespFactory.getResp(request, ConstantReturnCode.MUSIC_SUCCESS);
        return resp;
    }
    
    @RequestMapping("/userchecklogin")
    @ResponseBody
    public BaseResp userCheckLogin(HttpServletRequest request,
        HttpServletResponse response)
    {
        logger.info("user check login control start...");
        UserSessionContent userSessionContent = new UserSessionContent();
        SimpleResp<UserSessionContent> resp = new SimpleResp<UserSessionContent>();
        
        // 判断是否刷新session
        if (USER_REFRESH_SESSION_FLAG)
        {
            UserSessionManage.refreshSession(request);
        }
        
        UserInfo userInfo = (UserInfo)request.getSession()
            .getAttribute(ConstantConfigs.SESSION_USERINFO);
        userSessionContent.setConfigInfos(UserSessionManage.getWebConfigs());
        userSessionContent.setUserInfo(userInfo);
        
        resp.setRecord(userSessionContent);
        resp.setResultInfo(RespFactory.getResultInfo(request,
            ConstantReturnCode.MUSIC_SUCCESS));
        
        if (!UserSessionManage.isUserOnline(request))
        {
            resp.setResultInfo(RespFactory.getResultInfo(request,
                ConstantReturnCode.MUSIC_SESSION_NULL));
        }
        return resp;
    }
}
